home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 43 / Amiga Format CD43 (1999)(Future Publishing)(GB)(Track 1 of 2)[!][issue 1999-09].iso / -serious- / programming / other / python-1.52 / lib / python1.5 / pyclbr.py < prev    next >
Text File  |  1999-06-14  |  7KB  |  223 lines

  1. '''Parse a Python file and retrieve classes and methods.
  2.  
  3. Parse enough of a Python file to recognize class and method
  4. definitions and to find out the superclasses of a class.
  5.  
  6. The interface consists of a single function:
  7.     readmodule(module, path)
  8. module is the name of a Python module, path is an optional list of
  9. directories where the module is to be searched.  If present, path is
  10. prepended to the system search path sys.path.
  11. The return value is a dictionary.  The keys of the dictionary are
  12. the names of the classes defined in the module (including classes
  13. that are defined via the from XXX import YYY construct).  The values
  14. are class instances of the class Class defined here.
  15.  
  16. A class is described by the class Class in this module.  Instances
  17. of this class have the following instance variables:
  18.     name -- the name of the class
  19.     super -- a list of super classes (Class instances)
  20.     methods -- a dictionary of methods
  21.     file -- the file in which the class was defined
  22.     lineno -- the line in the file on which the class statement occurred
  23. The dictionary of methods uses the method names as keys and the line
  24. numbers on which the method was defined as values.
  25. If the name of a super class is not recognized, the corresponding
  26. entry in the list of super classes is not a class instance but a
  27. string giving the name of the super class.  Since import statements
  28. are recognized and imported modules are scanned as well, this
  29. shouldn't happen often.
  30.  
  31. BUGS
  32. Continuation lines are not dealt with at all and strings may confuse
  33. the hell out of the parser, but it usually works.''' # ' <-- bow to font lock
  34.  
  35. import os
  36. import sys
  37. import imp
  38. import re
  39. import string
  40.  
  41. id = '[A-Za-z_][A-Za-z0-9_]*'    # match identifier
  42. blank_line = re.compile('^[ \t]*($|#)')
  43. is_class = re.compile('^class[ \t]+(?P<id>'+id+')[ \t]*(?P<sup>\([^)]*\))?[ \t]*:')
  44. is_method = re.compile('^[ \t]+def[ \t]+(?P<id>'+id+')[ \t]*\(')
  45. is_import = re.compile('^import[ \t]*(?P<imp>[^#;]+)')
  46. is_from = re.compile('^from[ \t]+(?P<module>'+id+'([ \t]*\\.[ \t]*'+id+')*)[ \t]+import[ \t]+(?P<imp>[^#;]+)')
  47. dedent = re.compile('^[^ \t]')
  48. indent = re.compile('^[^ \t]*')
  49.  
  50. _modules = {}                # cache of modules we've seen
  51.  
  52. # each Python class is represented by an instance of this class
  53. class Class:
  54.     '''Class to represent a Python class.'''
  55.     def __init__(self, module, name, super, file, lineno):
  56.         self.module = module
  57.         self.name = name
  58.         if super is None:
  59.             super = []
  60.         self.super = super
  61.         self.methods = {}
  62.         self.file = file
  63.         self.lineno = lineno
  64.  
  65.     def _addmethod(self, name, lineno):
  66.         self.methods[name] = lineno
  67.  
  68. def readmodule(module, path=[], inpackage=0):
  69.     '''Read a module file and return a dictionary of classes.
  70.  
  71.     Search for MODULE in PATH and sys.path, read and parse the
  72.     module and return a dictionary with one entry for each class
  73.     found in the module.'''
  74.  
  75.     i = string.rfind(module, '.')
  76.     if i >= 0:
  77.         # Dotted module name
  78.         package = string.strip(module[:i])
  79.         submodule = string.strip(module[i+1:])
  80.         parent = readmodule(package, path, inpackage)
  81.         child = readmodule(submodule, parent['__path__'], 1)
  82.         return child
  83.  
  84.     if _modules.has_key(module):
  85.         # we've seen this module before...
  86.         return _modules[module]
  87.     if module in sys.builtin_module_names:
  88.         # this is a built-in module
  89.         dict = {}
  90.         _modules[module] = dict
  91.         return dict
  92.  
  93.     # search the path for the module
  94.     f = None
  95.     if inpackage:
  96.         try:
  97.             f, file, (suff, mode, type) = \
  98.                 imp.find_module(module, path)
  99.         except ImportError:
  100.             f = None
  101.     if f is None:
  102.         fullpath = list(path) + sys.path
  103.         f, file, (suff, mode, type) = imp.find_module(module, fullpath)
  104.     if type == imp.PKG_DIRECTORY:
  105.         dict = {'__path__': [file]}
  106.         _modules[module] = dict
  107.         # XXX Should we recursively look for submodules?
  108.         return dict
  109.     if type != imp.PY_SOURCE:
  110.         # not Python source, can't do anything with this module
  111.         f.close()
  112.         dict = {}
  113.         _modules[module] = dict
  114.         return dict
  115.  
  116.     cur_class = None
  117.     dict = {}
  118.     _modules[module] = dict
  119.     imports = []
  120.     lineno = 0
  121.     while 1:
  122.         line = f.readline()
  123.         if not line:
  124.             break
  125.         lineno = lineno + 1    # count lines
  126.         line = line[:-1]    # remove line feed
  127.         if blank_line.match(line):
  128.             # ignore blank (and comment only) lines
  129.             continue
  130. ##         res = indent.match(line)
  131. ##         if res:
  132. ##             indentation = len(string.expandtabs(res.group(0), 8))
  133.         res = is_import.match(line)
  134.         if res:
  135.             # import module
  136.             for n in string.splitfields(res.group('imp'), ','):
  137.                 n = string.strip(n)
  138.                 try:
  139.                     # recursively read the
  140.                     # imported module
  141.                     d = readmodule(n, path, inpackage)
  142.                 except:
  143.                     print 'module',n,'not found'
  144.                     pass
  145.             continue
  146.         res = is_from.match(line)
  147.         if res:
  148.             # from module import stuff
  149.             mod = res.group('module')
  150.             names = string.splitfields(res.group('imp'), ',')
  151.             try:
  152.                 # recursively read the imported module
  153.                 d = readmodule(mod, path, inpackage)
  154.             except:
  155.                 print 'module',mod,'not found'
  156.                 continue
  157.             # add any classes that were defined in the
  158.             # imported module to our name space if they
  159.             # were mentioned in the list
  160.             for n in names:
  161.                 n = string.strip(n)
  162.                 if d.has_key(n):
  163.                     dict[n] = d[n]
  164.                 elif n == '*':
  165.                     # only add a name if not
  166.                     # already there (to mimic what
  167.                     # Python does internally)
  168.                     # also don't add names that
  169.                     # start with _
  170.                     for n in d.keys():
  171.                         if n[0] != '_' and \
  172.                            not dict.has_key(n):
  173.                             dict[n] = d[n]
  174.             continue
  175.         res = is_class.match(line)
  176.         if res:
  177.             # we found a class definition
  178.             class_name = res.group('id')
  179.             inherit = res.group('sup')
  180.             if inherit:
  181.                 # the class inherits from other classes
  182.                 inherit = string.strip(inherit[1:-1])
  183.                 names = []
  184.                 for n in string.splitfields(inherit, ','):
  185.                     n = string.strip(n)
  186.                     if dict.has_key(n):
  187.                         # we know this super class
  188.                         n = dict[n]
  189.                     else:
  190.                         c = string.splitfields(n, '.')
  191.                         if len(c) > 1:
  192.                             # super class
  193.                             # is of the
  194.                             # form module.class:
  195.                             # look in
  196.                             # module for class
  197.                             m = c[-2]
  198.                             c = c[-1]
  199.                             if _modules.has_key(m):
  200.                                 d = _modules[m]
  201.                                 if d.has_key(c):
  202.                                     n = d[c]
  203.                     names.append(n)
  204.                 inherit = names
  205.             # remember this class
  206.             cur_class = Class(module, class_name, inherit, file, lineno)
  207.             dict[class_name] = cur_class
  208.             continue
  209.         res = is_method.match(line)
  210.         if res:
  211.             # found a method definition
  212.             if cur_class:
  213.                 # and we know the class it belongs to
  214.                 meth_name = res.group('id')
  215.                 cur_class._addmethod(meth_name, lineno)
  216.             continue
  217.         if dedent.match(line):
  218.             # end of class definition
  219.             cur_class = None
  220.     f.close()
  221.     return dict
  222.  
  223.